<?php
namespace Admin\Controller;
use Common\Controller\AdminbaseController;
use Common\Model\LiveChannelModel;

class LiveChannelController extends AdminbaseController {
	
	private $live_channel;
	private $live_push_operator;
	private $live_channel_operator;
	
	function _initialize() {
		parent::_initialize();
		$this->live_channel = D("Common/LiveChannel");
		$this->live_push_operator = D("Common/LivePushOperator");
		$this->live_channel_operator = D("Common/LiveChannelOperator");
	}
	
	function index(){
		$status = I("post.status", -1);
		$name = I("post.name", "");

		$config = array('SecretId'       => C("API_SecretId"),
				'SecretKey'      => C("API_SecretKey"),
				'RequestMethod'  => 'GET',
				'DefaultRegion'  => C("API_DefaultRegion"));
		
		vendor("QcloudApi.QcloudApi");
		$service = \QcloudApi::load(\QcloudApi::MODULE_LIVE, $config);

		$pageNo = I('p',1);
		if(null == $pageNo){
			$pageNo = 1;
		}
		$package = array(
				'pageSize' => 20,
				'pageNo'=> $pageNo
		);
		if(0 == $status){
			$package['channelStatus'] = 3;
		}
		$a = $service->DescribeLVBChannelList($package);
		\Think\Log::record('腾讯云返回：'.json_encode($a), 'INFO');
		if($a == false){
			\Think\Log::record('腾讯云返回：'.json_encode($service->getError()), 'INFO');
			return $this->error("调用腾讯云接口错误：".$service->getError()->getMessage());
		}else{
			$count = $a['all_count'];
			$page = $this->page($count, 20);
			$channelSet = $a['channelSet'];
			$result = array();
			if($channelSet && !empty($channelSet)){
				foreach($channelSet as $key=>$value){
					$channel = $this->live_channel->where(array('txy_channel_id'=>$value['channel_id']))->find();
					$channel['push_url'] = str_replace('MP4', 'mp4', $channel['push_url']);
					if (3 == $channel['device_type']) {
						$channel['push_operator'] = $this->live_channel->getOperatorByChannelId($channel['channel_id']);
					}
					if ('1' == $value['channel_status']) {
						//有输入流
						$channel['push_status'] = 1;
					} else {
						//无输入流
						$channel['push_status'] = 0;
					}
					$result[] = $channel;
				}
			}
			$admin_id = $_SESSION['ADMIN_ID'];
			$this->assign("admin_id", $admin_id);
			$this->assign("data", $result);
			$this->assign("formParam", array('status'=>$status,'name'=>$name));
			$this->assign("page", $page->show('Admin'));
			$this->display();
		}
		
		/*$count = $this->live_channel->queryLiveChannelCount($status, $name);
		$page = $this->page($count, 20);
		
		$result = $this->live_channel->queryLiveChannelList($status, $name, $page->firstRow , $page->listRows);
		
		if($result && !empty($result)){
			foreach($result as $key=>&$value){
				$value['push_operator'] = $this->live_channel->getOperatorByChannelId($value['channel_id']);
			}
		}
		
		$this->assign("data", $result);
		$this->assign("formParam", array('status'=>$status,'name'=>$name));
		$this->assign("page", $page->show('Admin'));
		$this->display();
		*/
	}
	
	function add(){
		$this->display();
	}
	
	function add_post(){
		if(IS_POST){
			$channelName = I("post.channel_name", '');
			if(empty($channelName)){
				return $this->error("频道名称不能为空！");
			}
			
			$status = I("post.status", 1);
			$channelDescribe = I("post.channel_describe", NULL);
			
			$config = array('SecretId'       => C("API_SecretId"),
					'SecretKey'      => C("API_SecretKey"),
					'RequestMethod'  => 'GET',
					'DefaultRegion'  => C("API_DefaultRegion"));

			vendor("QcloudApi.QcloudApi");
			$service = \QcloudApi::load(\QcloudApi::MODULE_LIVE, $config);
			$package = array('channelName' => $channelName,
                    'channelDescribe' => $channelDescribe,
					'outputSourceType'=>3,//1 RTMP输出 2  HLS输出 3 RTMP 和HLS输出
					//'sourceList'=>array(array('name'=>'test','type'=>1))
                );
			$package['sourceList.1.name'] = 'test';
			$package['sourceList.1.type'] = 1;
			$a = $service->CreateLVBChannel($package);
			\Think\Log::record('腾讯云返回：'.json_encode($a), 'INFO');
			if($a == false){
				return $this->error("调用腾讯云接口错误：".$service->getError()->getMessage());
			}else{
				$channelId = $a['channel_id'];
				//创建成功 创建录播任务
				$param = array('channelId' => $channelId,
						'endTime' => '2030-12-31 12:00:00'
				);
				$b = $service->CreateRecord($param);
				if($a == false){
					return $this->error("调用腾讯云接口错误：".$service->getError()->getMessage());
				}else {
					$channelInfo = $a['channelInfo'];
					$upstream_address = $channelInfo['upstream_address'].'&record=MP4';
					$downstream_address = $channelInfo['downstream_address'][0]['hls_downstream_address'];
					$taskId = $b['task_id'];
					$manager = I("post.manager", NULL);
					$managerPhone = I("post.manager_phone", NULL);
					
					$deviceType   = I("post.device_type", 1);
					$channel_type = I("post.channel_type",0);
					$creatorId = $_SESSION["ADMIN_ID"];
					$postData = array(
							'txy_channel_id'=>$channelId,
							'channel_name'=>$channelName,
							'task_id'=>$taskId,
							'channel_describe'=>$channelDescribe,
							'device_type'=>$deviceType,
							'manager'=>$manager,
							'manager_phone'=>$managerPhone,
							'status'=>$status,
							'push_url'=>$upstream_address,
							'pull_url'=>$downstream_address,
							'create_time'=>date('Y-m-d H:i:s'),
							'creator_id'=>$creatorId,
							'type'=>$channel_type,
					);
					$result = $this->live_channel->add($postData);
					if($result){
						$this->success("添加成功！", U("Admin/LiveChannel/index"));
					}else{
						return $this->error("添加失败！");
					}
				}
			}
			
		}
	}
	
	function edit(){
		$channelId = I("channelId", 0);
		$result = $this->live_channel->where(array('channel_id'=>$channelId))->find();
		$this->assign($result);
		$this->display();
	}
	
	function edit_post(){
		if(IS_POST){
			$channelName = I("post.channel_name", '');
			if(empty($channelName)){
				return $this->error("频道名称不能为空！");
			}
			$channelId = I("post.channel_id", 0);
			$channelDescribe = I("post.channel_describe", NULL);
			$manager = I("post.manager", NULL);
			$managerPhone = I("post.manager_phone", NULL);
			$postData = array(
					'channel_name'=>$channelName,
					'channel_describe'=>$channelDescribe,
					'manager'=>$manager,
					'manager_phone'=>$managerPhone
			);
			$result = $this->live_channel->where(array('channel_id'=>$channelId))->save($postData);
			if($result){
				$this->success("修改成功！", U("Admin/LiveChannel/index"));
			}else{
				return $this->error("修改失败！");
			}
		}
	}
	
	function disable(){
		$channelId = I("get.channelId", 0);
		$txyChannelId = I("get.txyChannelId", 0);
		$status = 0;
		$config = array('SecretId'       => C("API_SecretId"),
				'SecretKey'      => C("API_SecretKey"),
				'RequestMethod'  => 'GET',
				'DefaultRegion'  => C("API_DefaultRegion"));
		
		vendor("QcloudApi.QcloudApi");
		$service = \QcloudApi::load(\QcloudApi::MODULE_LIVE, $config);
		$package = array('channelIds.1' => $txyChannelId);
		$a = $service->StopLVBChannel($package);
		\Think\Log::record('腾讯云返回：'.json_encode($a), 'INFO');
		if($a == false){
			return $this->error("调用腾讯云接口错误：".$service->getError()->getMessage());
		}else{
			$postData = array(
					'status'=>$status
			);
			$result = $this->live_channel->where(array('channel_id'=>$channelId))->save($postData);
			if($result){
				$this->success("禁用成功！", U("Admin/LiveChannel/index"));
			}else{
				return $this->error("禁用失败！");
			}
		}
	}
	
	function enable(){
		$channelId = I("get.channelId", 0);
		$txyChannelId = I("get.txyChannelId", 0);
		$status = 1;
		$config = array('SecretId'       => C("API_SecretId"),
				'SecretKey'      => C("API_SecretKey"),
				'RequestMethod'  => 'GET',
				'DefaultRegion'  => C("API_DefaultRegion"));
		
		vendor("QcloudApi.QcloudApi");
		$service = \QcloudApi::load(\QcloudApi::MODULE_LIVE, $config);
		$package = array('channelIds.1' => $txyChannelId);
		$a = $service->StartLVBChannel($package);
		\Think\Log::record('腾讯云返回：'.json_encode($a), 'INFO');
		if($a == false){
			return $this->error("调用腾讯云接口错误：".$service->getError()->getMessage());
		}else{
			$postData = array(
					'status'=>$status
			);
			$result = $this->live_channel->where(array('channel_id'=>$channelId))->save($postData);
			if($result){
				$this->success("启用成功！", U("Admin/LiveChannel/index"));
			}else{
				return $this->error("启用失败！");
			}
		}
	}
	
	function edit_operator(){
		$channelId = I("get.channel_id", 0);
		
		$operatorList = $this->live_channel->getOperatorListByChannelId($channelId);
		
		$this->assign("channel_id", $channelId);
		$this->assign("operatorList", $operatorList);
		
		$this->display();
	}
	
	function edit_operator_post(){
		$channelId = I("post.channel_id", 0);
		//先删除
		$this->live_channel_operator->where(array("channel_id" => $channelId))->delete();
		$operatorIds = I("post.operatorIds", "");
	    //添加
        $operatorIdArray = explode(',', $operatorIds);
        foreach($operatorIdArray as $key=>$value){
        	$dataList[] = array('channel_id'=>$channelId, 'operator_id'=>$value);
        }
        
        $rid = $this->live_channel_operator->addAll($dataList);
        
        if (!empty($rid)) {
            $this->success("修改成功", U("Admin/LiveChannel/index"));
        } else {
            $this->error('修改失败');
        }
	}
	
	function view_live(){
		$channelId = I("get.channel_id", 0);
		$this->assign("channel_id", $channelId);
		$this->assign("app_id", C('API_AppId'));
		$this->display();
	}
}